package impl;

import anaydis.sort.SorterType;

import java.util.Comparator;
import java.util.List;

public class QuickSorter extends AbstractSorter{
    public QuickSorter(){
        super(SorterType.QUICK);
    }

    public <T> void sort(Comparator<T> comparator, List<T> list){
        miniSort(comparator, list, 0, list.size() - 1);
    }

    private <T> void miniSort(Comparator<T> comparator, List<T> list, int inicio, int fin){
        if (inicio >= fin) return;

        int w = inicio - 1;
        int v = fin;

        while (true) {
            while (greater(comparator, list, fin, ++w)){
                if (w == fin)  break;
            }
            while (greater(comparator, list, --v, fin)){
                if (v <= inicio) break;
            }
            if ((v <= w)){
                swap(list, w, fin);
                break;
            } else{
                swap(list, w, v);
            }
        }
        miniSort(comparator, list, inicio, w-1);
        miniSort(comparator, list, w+1, fin);
    }
}
